// 获取应用实例
const app = getApp();

// 初始化数据库
const db = wx.cloud.database();
const message = db.collection("message");
const uimg = db.collection("uimg");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    theme: 1,
    zone: 1,
    msgList: [],
    avatarUrl: "",
    nickname: "",
    openid: "",
    o_openid: "",
    isLoading: false,
    textarea: "",
    showTextarea: "",
    showLongpress: "",
    auto_focus: false,
    type: "",
    clicktime: "",
    _time: "",

    navHeight: app.globalData.navBarHeight,
    menuHeight: app.globalData.menuHeight,
    menuRight: app.globalData.menuRight,
    menuTop: app.globalData.menuTop,

    timer: null,
  },

  // 获取数据
  getMsgData(openid) {
    // wx.showLoading({
    //   title: "Loading...",
    // });
    message.where({ _openid: openid }).get({
      success: (res) => {
        // if (res.data.length == 0) {
        //   message.add({
        //     data: {
        //       myMsg: [],
        //       avatarUrl: wx.getStorageSync("avatarUrl"),
        //       nickname: wx.getStorageSync("nickname"),
        //     },
        //     success: () => { },
        //     fail: () => {
        //       wx.showToast({
        //         title: "初始化失败",
        //         icon: "error",
        //       });
        //     },
        //     complete: () => {
        //       wx.stopPullDownRefresh();
        //       wx.hideLoading();
        //     },
        //   });
        // } else {
        wx.stopPullDownRefresh();
        this.setData({
          msgList: res.data[0].myMsg,
          isLoading: false,
          avatarUrl: res.data[0].avatarUrl,
          nickname: res.data[0].nickname,
          zone: 1,
        });

        wx.hideLoading();
        // }
      },
      fail: () => {
        wx.showToast({
          title: "获取失败",
          icon: "none",
        });
      },
      complete: () => {
        wx.stopPullDownRefresh();
        wx.hideLoading();
      },
    });
  },

  // 删除留言
  del(e) {
    const { time } = e.currentTarget.dataset;
    let { openid, msgList } = this.data;
    const that = this;
    wx.showModal({
      title: "确认删除",
      content: "请确认是否要删除此留言，一经删除不可恢复",
      success: (result) => {
        if (result.confirm) {
          const delMsg = msgList.filter((i) => i.time == time);
          msgList = msgList.filter((i) => i.time != time);
          const delMsgImg = delMsg[0].images;

          message.where({ _openid: openid }).update({
            data: {
              myMsg: msgList,
            },
            success: function (res) {
              if (delMsgImg.length != 0) {
                delMsgImg.forEach((i) => {
                  wx.cloud.deleteFile({
                    fileList: [i.fileId],
                    success(res) {
                      console.log(res, '删除文件')
                    },
                    fail(err) {
                      console.log(err)
                    }
                  });
                })
              }
              wx.showToast({
                title: "删除成功",
                icon: "success",
              });
              that.getMsgData(openid);
            },
            fail: (err) => {
              wx.showToast({
                title: "删除失败",
                icon: "error",
              });
            },
          });
        }
      },
    });
  },

  // 图片预览
  clickPreview(e) {
    const { index, img } = e.currentTarget.dataset;
    let urls = [];
    for (var itm in img) {
      urls.push(img[itm].url);
    }
    wx.previewImage({
      current: urls[index], // 当前显示图片的 http 链接
      urls, // 需要预览的图片 http 链接列表
    });
  },
  shareMsgImg(e) {
    const { index, img } = e.currentTarget.dataset;
    const current = img.filter((item, idx) => idx == index);
    wx.showLoading({
      title: '加载中...',
    })
    wx.downloadFile({
      url: current[0].url,
      success: (res) => {
        wx.hideLoading();
        wx.showShareImageMenu({
          path: res.tempFilePath,
          style: 'v2',
          needShowEntrance: true,
          entrancePath: 'pages/login/login',
        })
      }
    })
  },

  changeMsg() {
    const that = this;
    const { openid, zone } = that.data;

    if (zone == 1) {
      wx.showModal({
        title: '动态切换',
        content: '是否查看对方动态',
        complete: (res) => {
          if (res.cancel) { }

          if (res.confirm) {
            wx.showLoading({
              title: "切换中...",
              mask: true,
            });
            uimg.where({ _openid: openid }).get({
              success: (res) => {
                if (res.data[0].o_openid) {
                  const o_openid = res.data[0].o_openid;
                  that.setData({
                    o_openid,
                  });
                  message.where({ _openid: o_openid }).get({
                    success: (result) => {
                      that.setData({
                        msgList: result.data[0].myMsg,
                        avatarUrl: result.data[0].avatarUrl,
                        nickname: result.data[0].nickname,
                        zone: 2,
                        showTextarea: "",
                      });
                    },
                    fail: () => {
                      wx.showToast({
                        title: "切换失败",
                        icon: "none",
                      });
                    },
                    complete: () => {
                      wx.hideLoading();
                    },
                  });
                } else {
                  wx.hideLoading();
                  wx.showModal({
                    title: "操作提醒",
                    content:
                      "你还没有绑定情侣，绑定后即可查看对方留言，如现在绑定请点击确定，不绑定请点击取消",
                    confirmColor: "#a5646d",
                    success: (result) => {
                      if (result.confirm) {
                        wx.navigateTo({
                          url: "/packageMine/pages/invitecode/invitecode",
                          success: (result) => { },
                          fail: () => { },
                          complete: () => { },
                        });
                      }
                    },
                    fail: () => { },
                    complete: () => { },
                  });
                }
                // console.log(res.data[0].o_openid);
              },
              fail: () => {
                wx.hideLoading();
                wx.showToast({
                  title: "切换失败",
                  icon: "none",
                });
              },
            });
          }
        }
      })
    } else {
      wx.showLoading({
        title: "切换中...",
        mask: true,
      });
      that.getMsgData(openid);
    }
  },

  writeBack(e) {
    const that = this;
    const { showTextarea } = that.data;
    const { time } = e.currentTarget.dataset;

    if (showTextarea == "") {
      that.setData({
        showTextarea: time,
        auto_focus: true,
        type: "writeBack",
      });
    } else {
      that.setData({
        showTextarea: "",
        auto_focus: false,
        type: "",
      });
    }
  },

  bindinput(e) {
    const { value } = e.detail;
    this.setData({
      textarea: value,
    });
  },

  bindconfirm(e) {
    const that = this;
    let { zone, msgList, o_openid, textarea, openid, type, clicktime, _time } =
      that.data;
    const { value } = e.detail;
    const { time } = e.currentTarget.dataset;
    if (value == "" || textarea == "") {
      wx.showToast({
        title: "内容为空",
        icon: "none",
      });
      that.setData({
        showTextarea: "",
        auto_focus: false,
      });
    } else {
      switch (type) {
        case "writeBack":
          msgList.forEach((i) => {
            if (i.time == time) {
              i.comment.push({
                value: textarea,
                avatarUrl: wx.getStorageSync("avatarUrl"),
                nickname: wx.getStorageSync("nickname"),
                time: +new Date(),
                openid,
                reply: [],
              });
            }
          });
          message.where({ _openid: o_openid }).update({
            data: {
              myMsg: msgList,
            },
            success: () => {
              message.where({ _openid: o_openid }).get({
                success: (res) => {
                  that.setData({
                    msgList: res.data[0].myMsg,
                    showTextarea: "",
                    textarea: "",
                  });
                },
              });
            },
          });
          break;

        case "reply":
          if (zone == 1) {
            message.where({ _openid: openid }).get({
              success: (res) => {
                let { myMsg } = res.data[0];
                console.log("我的", myMsg);
                myMsg.forEach((item) => {
                  if (item.time == clicktime) {
                    item.comment.forEach((i) => {
                      if (i.time == _time) {
                        i.reply.push({
                          replyvalue: textarea,
                          avatarUrl: wx.getStorageSync("avatarUrl"),
                          nickname: wx.getStorageSync("nickname"),
                          time: +new Date(),
                          openid,
                        });
                        return;
                      }
                    });
                    return;
                  }
                });
                message.where({ _openid: openid }).update({
                  data: {
                    myMsg,
                  },
                  success: () => {
                    wx.showToast({
                      title: "回复成功",
                      icon: "none",
                    });
                    that.setData({
                      msgList: myMsg,
                      showTextarea: "",
                      textarea: "",
                    });
                  },
                });
              },
            });
          } else {
            message.where({ _openid: o_openid }).get({
              success: (res) => {
                let { myMsg, avatarUrl, nickname } = res.data[0];
                console.log("对方", myMsg);
                myMsg.forEach((item) => {
                  if (item.time == clicktime) {
                    item.comment.forEach((i) => {
                      if (i.time == _time) {
                        i.reply.push({
                          replyvalue: textarea,
                          avatarUrl: wx.getStorageSync("avatarUrl"),
                          nickname: wx.getStorageSync("nickname"),
                          time: +new Date(),
                          openid,
                        });
                        return;
                      }
                    });
                    return;
                  }
                });
                console.log(myMsg);
                message.where({ _openid: o_openid }).update({
                  data: {
                    myMsg,
                  },
                  success: () => {
                    wx.showToast({
                      title: "回复成功",
                      icon: "none",
                    });
                    that.setData({
                      msgList: myMsg,
                      showTextarea: "",
                    });
                  },
                });
              },
            });
          }
          break;

        case "replyReply":
          console.log("replyReply");
          break;

        default:
          wx.showToast({
            title: "开发中",
            icon: "none",
          });
          break;
      }
    }
  },

  touchstart() {
    this.setData({
      showLongpress: "",
      showTextarea: "",
    });
  },

  longpress(e) {
    const { time } = e.currentTarget.dataset;
    this.setData({
      showLongpress: time,
    });
  },

  delComment(e) {
    const { time, _time, type } = e.currentTarget.dataset;
    const { zone, openid, o_openid } = this.data;
    const that = this;

    switch (type) {
      case "delComment":
        if (zone == 1) {
          message.where({ _openid: openid }).get({
            success: (res) => {
              let { myMsg } = res.data[0];
              console.log("对方", myMsg);
              myMsg.forEach((item) => {
                if (item.time == time) {
                  item.comment = item.comment.filter((i) => i.time != _time);
                  return;
                }
              });
              message.where({ _openid: openid }).update({
                data: {
                  myMsg,
                },
                success: () => {
                  wx.showToast({
                    title: "删除成功",
                    icon: "none",
                  });
                  that.setData({
                    msgList: myMsg,
                  });
                },
              });
            },
          });
        } else {
          message.where({ _openid: o_openid }).get({
            success: (res) => {
              let { myMsg } = res.data[0];
              console.log("对方", myMsg);
              myMsg.forEach((item) => {
                if (item.time == time) {
                  item.comment = item.comment.filter((i) => i.time != _time);
                  return;
                }
              });
              console.log(myMsg);

              message.where({ _openid: o_openid }).update({
                data: {
                  myMsg,
                },
                success: () => {
                  wx.showToast({
                    title: "删除成功",
                    icon: "none",
                  });
                  that.setData({
                    msgList: myMsg,
                  });
                },
              });
            },
          });
        }
        break;

      case "delReply":
        wx.showToast({
          title: "开发中",
          icon: "none",
        });
        break;
    }
  },
  replyComment(e) {
    const { time, _time, type } = e.currentTarget.dataset;
    this.setData({
      showTextarea: time,
      auto_focus: true,
      showLongpress: "",
      type,
      clicktime: time,
      _time,
    });
  },

  copyCon(e) {
    const { con } = e.currentTarget.dataset;
    wx.setClipboardData({
      data: con,
      success(res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // const openid = wx.getStorageSync("openid");
    // wx.showLoading({
    //   title: "Loading...",
    //   mask: "true",
    // });
    // this.getMsgData(openid);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1,
        theme: app.globalData.theme,
      });
    }
    let { openid, o_openid } = this.data;
    openid = wx.getStorageSync("openid");
    o_openid = wx.getStorageSync("o_openid");
    this.setData({
      openid,
      o_openid,
      theme: app.globalData.theme,
    });
    const { theme } = this.data;
    if (theme == 1) {
      wx.setTabBarStyle({
        backgroundColor: "#a5646d",
      });
    } else if (theme == 2) {
      wx.setTabBarStyle({
        backgroundColor: "#1a1a1a",
      });
    } else if (theme == 3) {
      wx.setTabBarStyle({
        backgroundColor: "#86C6F6",
      });
    }

    this.getMsgData(openid);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({
      showLongpress: "",
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    const { zone } = this.data;
    const openid = wx.getStorageSync("openid");
    this.setData({
      isLoading: true,
    });
    this.onRefresh(openid);
  },

  onRefresh(openid) {
    // const { openid } = this.data;
    wx.showLoading({
      title: "Loading...",
      mask: "true",
    });

    this.getMsgData(openid);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
